<?php
/**
 * Created by PhpStorm.
 * User: Yuan
 * Date: 2016/11/16
 * Time: 23:34
 */

// 回复单文本
function responseText($postObj, $content, $debug = '')
{
    $template = "<xml>
		<ToUserName><![CDATA[%s]]></ToUserName>
		<FromUserName><![CDATA[%s]]></FromUserName>
		<CreateTime>%s</CreateTime>
		<MsgType><![CDATA[%s]]></MsgType>
		<Content><![CDATA[%s]]></Content>
		</xml>";
    //注意模板中的中括号 不能少 也不能多
    $fromUser = $postObj->ToUserName;
    $toUser = $postObj->FromUserName;
    $time = time();
    $msgType = 'text';

    /*if($debug) {
        $content .='<br>公众号id--'.$fromUser;
        $content .='<br>用户id--'.$toUser;
        $content .='<br>消息类型--'.$postObj->MsgType;
        $content .='<br>事件类型--'.$postObj->Event;
        $content .='<br>内容--'.$postObj->Content;
        if (strtoupper($postObj->Event) == 'SCAN') {
            //扫码
            $content .='<br>事件KEY值--'.$postObj->EventKey;
            $content .='<br>二维码的ticket--'.$postObj->Ticket;
        } elseif (strtoupper($postObj->Event) == 'LOCATION') {
            //发送位置
            $content .='<br>地理位置纬度--'.$postObj->Latitude;
            $content .='<br>地理位置经度--'.$postObj->Longitude;
            $content .='<br>地理位置精度--'.$postObj->Precision;
        } elseif (strtoupper($postObj->Event) == 'VIEW') {
            //点击菜单跳转链接时的事件推送
            $content .= '<br>事件KEY值，设置的跳转URL--'.$postObj->EventKey;
        } elseif (strtolower($postObj->Event) == 'subscribe') {
            //关注
            if ($postObj->EventKey && $postObj->Ticket) {
                $content .='<br>事件KEY值--'.$postObj->EventKey;
                $content .='<br>二维码的ticket--'.$postObj->Ticket;
            }
        }
    }*/
    echo sprintf($template, $toUser, $fromUser, $time, $msgType, $content);
}

//回复多图文类型的微信消息
function responseNews($postObj, $arr)
{
    $toUser = $postObj->FromUserName;
    $fromUser = $postObj->ToUserName;
    $template = "<xml>
					<ToUserName><![CDATA[%s]]></ToUserName>
					<FromUserName><![CDATA[%s]]></FromUserName>
					<CreateTime>%s</CreateTime>
					<MsgType><![CDATA[%s]]></MsgType>
					<ArticleCount>" . count($arr) . "</ArticleCount>
					<Articles>";
    foreach ($arr as $k => $v) {
        $template .= "<item>
						<Title><![CDATA[" . $v['title'] . "]]></Title> 
						<Description><![CDATA[" . $v['description'] . "]]></Description>
						<PicUrl><![CDATA[" . $v['picUrl'] . "]]></PicUrl>
						<Url><![CDATA[" . $v['url'] . "]]></Url>
						</item>";
    }

    $template .= "</Articles>
					</xml> ";
    echo sprintf($template, $toUser, $fromUser, time(), 'news');
}

/**
 * 杜李宏
 * get请求
 * @param $getUrl
 * @return mixed
 */
function get_oneself($getUrl)
{
    //$getUrl = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.APPID.'&secret='.SECRET;
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $getUrl);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    //curl_setopt($ch, CURL_SSLVERSION_SSL, 2);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    $data = curl_exec($ch);
    $response = json_decode($data, true);
    curl_close($ch);
    return $response;
}

/**
 * 杜李宏
 * @POST请求
 */
function post_oneself($url, $params = array())
{
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    if ($params) {
        curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
    }
    $data = curl_exec($ch);
    curl_close($ch);
    return json_decode($data, true);
}

/*function post_oneself($url,$params = array()) {
    $ch = curl_init();
    $header = "Accept-Charset: utf-8";
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $data = curl_exec($ch);
    if (curl_errno($ch)) {
        curl_close( $ch );
        return $ch;
    }else{
        curl_close( $ch );
        return json_decode($data,true);
    }

}*/

/**
 * 首页重新生成redis缓存
 * @param $getUrl
 * @return mixed
 */
function get_curl($local_id, $url)
{
    if (empty($url)) {
        $url = 'http://' . $_SERVER['SERVER_NAME'] . '/store/index/local_id/' . $local_id;
    }
    $Cache = Think\Cache::getInstance('Redis');

    $Cache->clear();
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    //curl_setopt($ch, CURL_SSLVERSION_SSL, 2);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
}

/**
 * 杜李宏
 * 获取access_token
 * @return bool|mixed
 */
function accessToken($type = false)
{
    $app_id = C('APPID');
    $secret = C('SECRET');
    if (!S('access_token') || $type) {
        $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . $app_id . '&secret=' . $secret;
        $data = get_oneself($url);
        if (isset($data['errcode']) && $data['errcode'] == 40013) {
            return false;
        }
        S('access_token', null);
        S('access_token', $data['access_token'], 7000);
    }
    return S('access_token');
}

/**
 * 根据键取值
 * @param $array
 * @param $key
 * @return mixed
 */
function search($array, $key)
{
    if (is_array($array)) {
        return $array[$key];
    }
    return $key;
}


/**
 * 店铺商品信息获取
 * @param $product_id 查询值
 * @param $filed 返回的值
 * @return mixed
 */
function get_store_product($product_id, $filed)
{
    $m = M('b2c_store_product');
    $where = ['local_id' => session('userInfo')['local_id'], 'product_id' => $product_id];
    $result = $m->where($where)->field($filed)->find();
    return $result[$filed];
}

/**
 * 根据goods_id获取一张缩略图和一张大图 用于预览功能
 * @param $goods_id
 * @return string
 */
function getThumb($goods_id)
{
    if (!$goods_id) {
        return '';
    }
    $images = M('b2c_goods a')
        ->join(C('DB_PREFIX') . 'image_image b on a.image_default_id=b.image_id', 'LEFT')
        ->field('l_url')
        ->where(array('goods_id' => $goods_id))
        ->find();

    return $images['l_url'] ? '/Uploads/' . $images['l_url'] : '';
}

/**获取原图
 * @param $goods_id
 * @return string
 */
function getOriginalImg($goods_id)
{
    if (!$goods_id) {
        return '';
    }
    $images = M('b2c_goods a')
        ->join(C('DB_PREFIX') . 'image_image b on a.image_default_id=b.image_id', 'LEFT')
        ->field('url')
        ->where(array('goods_id' => $goods_id))
        ->find();

    return $images['url'] ? '/Uploads/' . $images['url'] : '';
}




/**
 * 获取店铺商品标签
 * @param $local_id
 * @param $product_id
 */
function getProductLabel($local_id, $product_id)
{
    $where = [
        'a.local_id' => $local_id,
        'b.local_id' => $local_id,
        'b.product_id' => $product_id,
    ];

    $store_products_label = M('store_products_label a');
    $labelMsg = $store_products_label->join(C('DB_PREFIX') . "store_products_label_relation b on a.label_id = b.label_id")
        ->where($where)
        ->select();
    $labelName = '';
    foreach ($labelMsg as $v) {
        $labelName .= "<span>" . $v['label_name'] . "</span>";
    }
    return $labelName;
}

/**
 * 经纬度算距离
 * @param $longitude1
 * @param $latitude1
 * @param $longitude2
 * @param $latitude2
 * @param int $unit 1表示米，2千米
 * @param int $decimal 精确到多少位
 * @return float
 */
function getDistance($longitude1, $latitude1, $longitude2, $latitude2, $unit = 1, $decimal = 2)
{

    $EARTH_RADIUS = 6370.996; // 地球半径系数
    $PI = 3.1415926;

    $radLat1 = $latitude1 * $PI / 180.0;
    $radLat2 = $latitude2 * $PI / 180.0;

    $radLng1 = $longitude1 * $PI / 180.0;
    $radLng2 = $longitude2 * $PI / 180.0;

    $a = $radLat1 - $radLat2;
    $b = $radLng1 - $radLng2;

    $distance = 2 * asin(sqrt(pow(sin($a / 2), 2) + cos($radLat1) * cos($radLat2) * pow(sin($b / 2), 2)));
    $distance = $distance * $EARTH_RADIUS * 1000;

    if ($unit == 2) {
        $distance = $distance / 1000;
    }

    return round($distance, $decimal);

}

/**
 * 获取地区
 * @return json
 */
function regions()
{
    $obj = M('area');
    $data_area = [];
    $data1 = $obj->where(['pid' => '0'])->select();
    //dump($data1);
    //echo $obj->_sql();
    $i = 0;
    foreach ($data1 as $k1 => $v1) {
        $data_area[$i]['id'] = $v1['id'];
        $data_area[$i]['name'] = $v1['name'];
        $data2 = $obj->where(['pid' => $v1['id']])->select();
        $j = 0;
        foreach ($data2 as $k2 => $v2) {
            $data_area[$i]['child'][$j]['id'] = $v2['id'];
            $data_area[$i]['child'][$j]['name'] = $v2['name'];
            $data3 = $obj->where(['pid' => $v2['id']])->select();
            $n = 0;
            foreach ($data3 as $k3 => $v3) {
                $data_area[$i]['child'][$j]['child'][$n]['id'] = $v3['id'];
                $data_area[$i]['child'][$j]['child'][$n]['name'] = $v3['name'];
                $n++;
            }
            $j++;
        }
        $i++;
    }
    //dump($data_area);die;
    return json_encode($data_area);
}

/**
 * 生成链接
 * @param $url
 * @param array $vars
 * @param bool $suffix
 * @param bool $domain
 * @return string
 */
function url($url, $vars = array(), $suffix = true, $domain = false)
{
    $url = trim($url);
    if (!isset($vars['local_id'])) {
        $local_id = I('get.local_id', 0);
        if (!$local_id) {
            $local_id = session('home_local_id') ? session('home_local_id') : 0;
            if (!$local_id) {
                $local_id = session('userInfo')['default_local_id'] ? session('userInfo')['default_local_id'] : 0;
                if (!$local_id) {
                    $local_id = session('t_userInfo')['default_local_id'];
                }
            }
        }
        $vars['local_id'] = $local_id;
    }
    if (!isset($vars['top_local_id'])) {
        $top_local_id = I('get.top_local_id', 0);
        //get为空或不为数字的时候取session
        if (!$top_local_id) {
            $top_local_id = session('top_home_local_id') ? session('top_home_local_id') : 11;
        }
        $vars['top_local_id'] = $top_local_id;
    }
    return U($url, $vars, $suffix, $domain);
}

/**
 * 订单状态
 * @param $status 订单状态
 * @param $pay_status 支付状态
 * @param $ship_status 发货状态
 * @param $received_status 收货状态
 * @param $refund_status 退款状态
 * @param $comment_status 评价状态
 * @param $sell_ago 售前 退款
 * @param $sell_front 售后 1退款、2退货退款
 * @return string
 */
function order_status($status, $pay_status, $ship_status, $received_status, $refund_status, $comment_status, $sell_ago, $sell_front)
{
    switch ($status) {
        case 'active' :
            if ($pay_status === '0') {
                return [1, '未支付'];
            }
            switch ($refund_status) {
                case '1' :
                    return [3, '退款完成'];
                case '2' :
                    return [5, '退货退款完成'];
            }
            if ($sell_ago || $sell_front) {
                return [2, '退款中'];
            }
            if ($ship_status === '0') {
                return [6, '未发货'];
            }

            if ($received_status === '0') {
                return [7, '已发货'];
            }

            if ($comment_status == '1') {
                return [8, '交易完成（待评价）'];
            } else if ($comment_status == '2') {
                return [9, '交易完成（已评价）'];
            }
            break;
        case 'dead' :
            return [10, '已失效'];
        case 'finish' :
            return [11, '交易完成'];
        case 'delete' :
            return [12, '已删除'];
    }
}

/**
 * @param $expTitle
 * @param $expCellName
 * @param $expTableData
 *
 * 使用方式
 * $xlsName  = "怡臣电子商务";
 * $xlsCell  = array(
 * array('0','账号序列'),
 * array('1','登录账户'),
 * array('2','账户昵称'),
 * array('3','222222222222')
 * );
 *
 * $xlsData  = array(
 * array('0' => '123', '1' => '234234234', '2' => '2222222222', '3'=>'222222222222'),
 * array('0' => '123', '1' => '234234234', '2' => '2222222222', '3'=>'222222222222'),
 * array('0' => '123', '1' => '234234234', '2' => '2222222222', '3'=>'222222222222'),
 * );
 * exportExcel($xlsName,$xlsCell,$xlsData);
 */
function exportExcel($expTitle, $expCellName, $expTableData)
{
    $xlsTitle = iconv('utf-8', 'gb2312', $expTitle);//文件名称
    $fileName = date('_YmdHis');//or $xlsTitle 文件名称可根据自己情况设定
    $cellNum = count($expCellName);
    $dataNum = count($expTableData);
    vendor("PHPExcel.PHPExcel");
    $objPHPExcel = new PHPExcel();
    $cellName = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'AA', 'AB', 'AC', 'AD', 'AE', 'AF', 'AG', 'AH', 'AI', 'AJ', 'AK', 'AL', 'AM', 'AN', 'AO', 'AP', 'AQ', 'AR', 'AS', 'AT', 'AU', 'AV', 'AW', 'AX', 'AY', 'AZ');

    $objPHPExcel->getActiveSheet(0)->mergeCells('A1:' . $cellName[$cellNum - 1] . '1');//合并单元格
    $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A1', $expTitle . '  导出时间:' . date('Y-m-d H:i:s'));
    for ($i = 0; $i < $cellNum; $i++) {
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue($cellName[$i] . '2', $expCellName[$i][1]);
    }
    // Miscellaneous glyphs, UTF-8
    for ($i = 0; $i < $dataNum; $i++) {
        for ($j = 0; $j < $cellNum; $j++) {
            $objPHPExcel->getActiveSheet(0)->setCellValue($cellName[$j] . ($i + 3), $expTableData[$i][$expCellName[$j][0]]);
        }
    }

    header('pragma:public');
    header('Content-type:application/vnd.ms-excel;charset=utf-8;name="' . $xlsTitle . '.xls"');
    header("Content-Disposition:attachment;filename=$fileName.xls");//attachment新窗口打印inline本窗口打印
    $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
    $objWriter->save('php://output');
    exit;
}

/**
 * 验证手机号是否正确
 * @param INT $mobile
 */
function isMobile($mobile)
{
    if (!is_numeric($mobile)) {
        return false;
    }
    return preg_match('#^13[\d]{9}$|^14[5,7]{1}\d{8}$|^15[^4]{1}\d{8}$|^17[\d]{9}$|^18[\d]{9}$#', $mobile) ? true : false;
}

function getGoodsCat($cat_id)
{
    $goods_cat = M('b2c_goods_cat')->field('cat_name')->where(['cat_id' => $cat_id])->find();
    return $goods_cat['cat_name'];
}

/**浮点型转半分比
 * @param $n
 * @return string
 */
function floatToPercent($n)
{
    return sprintf("%01.2f", $n * 100) . '%';
}

/**
 * 判断店铺商品是否在订单促销中
 */
function goods_is_Order_promotion($store_product_id, $local_id)
{
    $date = date('Y-m-d H:i:s', time());
    // 订单促销
    $promotion = M('b2c_store_order_promotion');
    $where['end_time'] = ['EGT', $date];
    $where['local_id'] = $local_id;
    $promotion_msg = $promotion->field('id,local_id,question_goods_id_array')->where($where)->order('sort asc')->select();

    foreach ($promotion_msg as $v) {
        $arr_goods = explode('#', $v['question_goods_id_array']);
        if (in_array($store_product_id, $arr_goods)) {
            return true;
        }
    }
    return false;
}


/**
 *  判断商品促销活动
 */

function store_goods($store_id, $local_id,$type=0)
{
    $date = time();
    $where['end_time'] = ['egt', $date];
    $where['local_id'] = $local_id;
    $where['store_id'] = $store_id;
    if ($type) {
        $where['type'] =$type;
    }

    $promotion = M('store_activity_product');
    $promotion_msg = $promotion->where($where)->find();
    if ($promotion_msg ==null) {
        return false;
    }
    return $promotion_msg;
}


/**
 * 判断店铺商品是否在商品促销中
 */
function goods_is_Goods_promotion($store_product_id, $local_id)
{
    $date = time();
    $promotion = M('b2c_store_goods_promotion');
    $where['end_time'] = ['egt', $date];
    $where['local_id'] = $local_id;
    $where['display']=1;
    $promotion_msg = $promotion->field('id,local_id,store_promotion')->where($where)->order('sort asc')->select();
    foreach ($promotion_msg as $v) {
        $store_promotion= json_decode($v['store_promotion']);
        $store_promotion= object_to_array($store_promotion);// 对象转数组
        $goods_idarray =array_keys($store_promotion); //取键名(store_id)
       // $arr_goods = explode(',', $store_promotion);
        if (in_array($store_product_id, $goods_idarray)) {
            return true;
        }
    }
    return false;
}

function object_to_array($obj) {
    $obj = (array)$obj;
    foreach ($obj as $k => $v) {
        if (gettype($v) == 'resource') {
            return;
        }
        if (gettype($v) == 'object' || gettype($v) == 'array') {
            $obj[$k] = (array)object_to_array($v);
        }
    }

    return $obj;
}
/**
 * 判断店铺商品是否在闪购中
 * @param $store_product_id
 * @return array
 */
function goods_is_shangou($store_product_id, $local_id)
{
    $info = M('starbuy_flashsales')
        ->alias('c')
        ->join(C('DB_PREFIX') . "starbuy_flashsales_goods a on a.special_id=c.special_id and a.store_pid = $store_product_id")
        ->join(C('DB_PREFIX') . 'starbuy_flashsales_time b on a.tid=b.tid')
        ->field('a.promotion_price,a.ini_y_tnum,a.initnum,a.repertory_num,a.countnum,a.store_pid,a.id,b.tid,b.limit,b.begin_time,b.end_time,c.is_start')
        ->where(['c.local_id' => $local_id])
        ->select();
    $time = time();
    foreach ($info as $k1 => &$v1) {
        //销毁过期的和未开始的
        if ($time < $v1['begin_time'] || $time >= $v1['end_time'] || $v1['is_start'] == '0' ) {
            unset($info[$k1]);
        }
    }
    sort($info);
    if ($info) {
        return true;
    } else {
        return false;
    }
}

/**
 * 判断店铺商品是否在选择的时间段内存在
 * @param $store_product_id
 * @param $local_id
 * @param $limitTime
 * @return bool
 */
function goods_is_shangou_by_limit_time($store_product_id, $local_id, $limitTime){
    $minTime = strtotime(date('Y-m-d'));//去掉当天以前的闪购商品
    $info = M('starbuy_flashsales a')
        ->join(C('DB_PREFIX') . 'starbuy_flashsales_time b on a.special_id=b.special_id and a.local_id='.$local_id, 'left')
        ->join(C('DB_PREFIX') . 'starbuy_flashsales_goods c on b.tid = c.tid', 'left')
        ->where(['c.store_pid' => $store_product_id, 'b.end_time' => ['gt', $minTime]])
        ->order('b.end_time desc')
        ->field(['b.begin_time', 'b.end_time'])
        ->select();
    $isBoolean = false;
    foreach ($info as $value){
        if (($value['begin_time'] >= strtotime($limitTime['beginTime']) && $value['begin_time'] <= strtotime($limitTime['endTime']))
            || (strtotime($limitTime['beginTime']) >= $value['begin_time'] && strtotime($limitTime['beginTime']) <= $value['end_time'])){
            $isBoolean = true;
            break;
        }
    }
    return $isBoolean;
}


/**查询商品是不是组合商品
 * @param $store_pid
 * @return bool
 */
function checkProductIsGroupPromotion($store_pid, $local_id)
{
    $time = time();
    $where = [
        'a.local_id' => $local_id,
        'a.state' => '1',
        'c.store_status' => 'true',
        'b.sp_id' => $store_pid,
        'a.start_time' => ['elt', $time],
        'a.end_time' => ['gt', $time],
    ];
    $exists = M('b2c_store_promotion_group')
        ->alias('a')
        ->join(C('DB_PREFIX') . 'b2c_store_promotion_group_item b on a.id=b.group_id')
        ->join(C('DB_PREFIX') . 'b2c_store_product c on b.sp_id=c.store_pid')
        ->where($where)
        ->count();
    return $exists ? true : false;
}

/**
 * 查询商品是否是专题商品包
 * @param $store_pid
 * @param $local_id
 * @return bool
 */
function checkProductIsSpecial($store_pid, $local_id)
{
    $where = [
        'local_id' => $local_id,
    ];
    $exists = M('b2c_special_type_store')
        ->field("goodids")
        ->where($where)
        ->select();

    $flag = false;
    if (empty($exists)) {
        return $flag;
    }
    // 判断
    for ($i = 0; $i < count($exists); $i++) {
        $arr = unserialize($exists[$i]['goodids']);
        if (in_array($store_pid, $arr)) {
            $flag = true;
        }
    }
    return $flag;
}


/**
 * 全国送 组合促销查询 供应商名字
 */

  function vendor_product($product_id,$local_id){
       $where['a.product_id'] =$product_id;
       $where['a.local_id'] =$local_id;
       $result = M('b2c_store_product a')
           ->join(C('DB_PREFIX') . 'qgs_supplier b on a.supplier_id=b.supplier_id')
           ->field('b.name,b.supplier_id')
           ->where($where)
           ->find();
      return $result;
  }

/**
 * 通过退款状态获取退款信息
 * $id b2c_refund_money表的主键
 * $status 退款状态，0审核失败,1用户申请，2店铺审核通过，3用户退货、填写物流, 4店铺确认退货, 5退货、退款完成,6用户重新申请,7用户取消申请
 * return
 */
function get_refund_goods_time($id, $status)
{
    $refund_money = M('b2c_refund_money')->field('json_msg')->where(['id' => $id])->find();
    $refund_money['json_msg'] = json_decode($refund_money['json_msg'], true);
    if ($refund_money) {
        switch ($status) {
            case 0:
                $time = $refund_money['json_msg']['a']['time'];
                break;
            case 1:
                $time = $refund_money['json_msg']['b']['time'];
                break;
            case 2:
                $time = $refund_money['json_msg']['c']['time'];
                break;
            case 3:
                $time = $refund_money['json_msg']['d']['time'];
                break;
            case 4:
                $time = $refund_money['json_msg']['e']['time'];
                break;
            case 5:
                $time = $refund_money['json_msg']['f']['time'];
                break;
            case 6:
                $time = $refund_money['json_msg']['g']['time'];
                break;
            case 7:
                $time = $refund_money['json_msg']['h']['time'];
                break;
            default :
                $time = false;
        }
        return date("Y-m-d H:i:s", $time);
    } else {
        return false;
    }
}

/**
 * 获取退货状态
 * 退款状态，0审核失败,1用户申请，2店铺审核通过，3用户退货、填写物流, 4店铺确认退货, 5退货、退款完成,6用户重新申请,7用户取消申请
 */
function get_refund_status($num)
{
    switch ($num) {
        case 0:
            $msg = '审核失败';
            break;
        case 1:
            $msg = '店铺审核中';
            break;
        case 2:
            $msg = '店铺审核通过';
            break;
        case 3:
            $msg = '已填写物流，等待确认';
            break;
        case 4:
            $msg = '店铺确认退货';
            break;
        case 5:
            $msg = '完成';
            break;
        case 6:
            $msg = '用户重新申请';
            break;
        case 7:
            $msg = '用户取消申请';
            break;
        default :
            return false;
    }
    return $msg;
}

/**
 * @param $refund_money_id 退款id
 *  获取退款商品信息
 */
function get_refund_goods($refund_money_id)
{
    $refund_money_goods = M('b2c_refund_money_goods')->where(['refund_money_id' => $refund_money_id])->select();
    if (!empty($refund_money_goods)) {
        $arr = '';
        foreach ($refund_money_goods as $k => $v) {
            $item = M('b2c_order_items')->where(['item_id' => $v['item_id']])->find();
            if ($item) {
                $arr .= "<font>" . $item['name'] . 'x' . $v['num'] . "</font> ";
            }
        }
    }
    return $arr;
}

/**
 * 获取会员信息
 */
function get_member_msg($member_id)
{
    $members = M('b2c_members')->where(['member_id' => $member_id])->find();
    return $members['nickname'];
}
/**
 * 根据店铺ID查店铺名字
 * @param $local_id
 * @return string
 */
function getStoreName($local_id){
    return M('webpos_local_store')->where(['local_id' => $local_id])->find()['local_name'];
}

/**
 * 供应商选择
 * @param $store_pid
 * @param $local_id
 * @return string
 */
function get_supplier_option($store_pid, $local_id, $supplier_id){

    $where = [
        'a.store_pid' => $store_pid,
        'a.local_id' => $local_id
    ];
    $store_product = M('qgs_supplier_store_product a')
        ->join(C('DB_PREFIX') . 'qgs_supplier b on a.supplier_id=b.supplier_id', 'left')
        ->field("b.supplier_id,b.name")
        ->where($where)
        ->select();
    $html = '';
    foreach ($store_product as $v) {
        if ($v['supplier_id'] == $supplier_id) {
            $html .= '<option selected="selected" value="'. $v['supplier_id'] .'" >'. $v['name'] .'</option>';
        }else{
            $html .= '<option value="'. $v['supplier_id'] .'" >'. $v['name'] .'</option>';
        }
    }

    return $html;
}

/**
 * ajax返回请求json格式数据
 * @param bool|true $status
 * @param string $message
 * @param array $data
 */
function ajax_json($status=true,$message='',$data=array())
{
    if ($status == true || $status ==false) {
        $result=array(
            'status'=>$status,
            'message'=>$message,
            'data'=>$data
        );
        echo json_encode($result);
        exit;
    }

}

/**
 * 随机数
 * @return string
 */
function getrandstr($num){
    $str='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890ABABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890CDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890';
    $randStr = str_shuffle($str);//打乱字符串
    $rands= substr($randStr,0,$num);//substr(string,start,length);返回字符串的一部分
    return $rands;
}

/**
 * 下属购物提成奖励
 * @param $member_id 会员
 * @param $local_id 店铺
 * @throws Exception
 */
function shoppingAward($member_id, $local_id, $order_id){
    // 判断当前店铺是否开启分销
    $webpos_local_store = M('webpos_local_store')->where(['local_id' => $local_id])->find();
    if (!empty($webpos_local_store) && $webpos_local_store['is_open_distribution'] == '1') {

        //查询分销上级会员是否存在
        $distribution_member = M('distribution_member')->where(['member_id' => $member_id, 'local_id' => $local_id])->find();

        if (empty($distribution_member)) {
            return true;
        }

        $b2c_orders = M('b2c_orders')->where(['order_id' => $order_id, 'local_id'=>$local_id])->find();
        $b2c_order_items = M('b2c_order_items')->where(['order_id' => $order_id])->select();

        // 查询下单比例
        $sdb_store_distribution_set = M('store_distribution_set')->where(['local_id' => $local_id, 'set_name' => 'son_shopping'])->find();

        $set_value = $sdb_store_distribution_set['set_value']/100;


        // 组合购买记录信息
        $msg = '';
        foreach ($b2c_order_items as $v){
            $msg .= ' ' . $v['name'];
        }

        if (!empty($distribution_member) && !empty($distribution_member['p_member_id']) && !empty($b2c_orders)) {

            // 订单金额
            $money = $b2c_orders['total_amount'];
            $wait_bonus = bcmul($money, $set_value, 2);

            $time = time();
            $data['local_id'] = $local_id;
            $data['member_id'] = $distribution_member['p_member_id'];
            $data['s_member_id'] = $member_id;
            $data['type'] = '0';
            $data['change'] = '3';
            $data['bonus_status'] = '1';
            $data['change_num'] = $wait_bonus;
            $data['param'] = $member_id.','.$order_id.','.$money;
            $data['time'] = $time;
            $data['msg'] = '购买了，'.$msg;
            $bonus_log = M('b2c_bonus_log')->add($data); // 奖金日志记录

            $p_member_id = $distribution_member['p_member_id'];

            // 累计奖金
            $distribution_member_up = M()->execute("update sdb_distribution_member set wait_bonus = wait_bonus + $wait_bonus where member_id=$p_member_id and local_id = $local_id");

            $queue_order_log_add['local_id'] = $local_id;
            $queue_order_log_add['member_id'] = $member_id;
            $queue_order_log_add['order_id'] = $order_id;
            $queue_order_log_add['p_member_id'] = $distribution_member['p_member_id'];
            $queue_order_log_add['order_money'] = $money;
            $queue_order_log_add['payed'] = $money * ($sdb_store_distribution_set['set_value']/100);
            $queue_order_log_add['create_time'] = date("Y-m-d H:i:s");
            $queue_order_log_add['msg'] = $msg;
            $b2c_queue_order_log_add = M('b2c_queue_order_log')->add($queue_order_log_add);
//            echo M()->getlastsql();exit;
            if ($bonus_log === false || $distribution_member_up === false || $b2c_queue_order_log_add === false) {
                return false;
            }else{
                return true;
            }
        } else {
            return true;
        }
    }else{
        return true;
    }
}

/**
 * 下属购物提成奖励 奖金支付
 * @param $member_id 会员
 * @param $local_id 店铺
 * @param $money 订单金额
 * @param $money 商品名称
 * @throws Exception
 */
function shoppingAwardBonus($member_id, $local_id, $order_id, $money, $msg){
    // 判断当前店铺是否开启分销
    $webpos_local_store = M('webpos_local_store')->where(['local_id' => $local_id])->find();
    if (!empty($webpos_local_store) && $webpos_local_store['is_open_distribution'] == '1') {

        //查询分销上级会员是否存在
        $distribution_member = M('distribution_member')->where(['member_id' => $member_id, 'local_id' => $local_id])->find();

        if (empty($distribution_member)) {
            return true;
        }

        // 查询下单比例
        $sdb_store_distribution_set = M('store_distribution_set')->where(['local_id' => $local_id, 'set_name' => 'son_shopping'])->find();

        $set_value = $sdb_store_distribution_set['set_value']/100;

        if (!empty($distribution_member) && !empty($distribution_member['p_member_id'])) {

            // 订单金额
            $wait_bonus = bcmul($money, $set_value, 2);

            $time = time();
            $data['local_id'] = $local_id;
            $data['member_id'] = $distribution_member['p_member_id'];
            $data['s_member_id'] = $member_id;
            $data['type'] = '0';
            $data['change'] = '3';
            $data['bonus_status'] = '1';
            $data['change_num'] = $wait_bonus;
            $data['param'] = $member_id.','.$order_id.','.$money;
            $data['time'] = $time;
            $data['msg'] = '购买了，'.$msg;
            $bonus_log = M('b2c_bonus_log')->add($data); // 奖金日志记录

            $p_member_id = $distribution_member['p_member_id'];

            // 累计奖金
            $distribution_member_up = M()->execute("update sdb_distribution_member set wait_bonus = wait_bonus + $wait_bonus where member_id=$p_member_id and local_id = $local_id");
            $queue_order_log_add['local_id'] = $local_id;
            $queue_order_log_add['member_id'] = $member_id;
            $queue_order_log_add['order_id'] = $order_id;
            $queue_order_log_add['p_member_id'] = $distribution_member['p_member_id'];
            $queue_order_log_add['order_money'] = $money;
            $queue_order_log_add['payed'] = $money * ($sdb_store_distribution_set['set_value']/100);
            $queue_order_log_add['create_time'] = date("Y-m-d H:i:s");
            $queue_order_log_add['msg'] = $msg;
            $b2c_queue_order_log_add = M('b2c_queue_order_log')->add($queue_order_log_add);
//            echo M()->getlastsql();exit;
            if ($bonus_log === false || $distribution_member_up === false || $b2c_queue_order_log_add === false) {
                return false;
            }else{
                return true;
            }
        }else{
            return true;
        }
    }else{
        return true;
    }
}

/**
 * 微信支付消息推送给上级会员
 * @param $member_id
 * @param $local_id
 * @param $order_id
 * @return int
 */
function WeixinPayPushToFatherMember($member_id,$local_id, $order_id){

    // 判断店铺是否开启分销功能
    $store = M('webpos_local_store')->where(['local_id' => $local_id])->find();
    if ($store['is_open_distribution'] == '0') {
        return false;
    }


    $b2c_orders = M('b2c_orders')->where(['order_id' => $order_id, 'local_id'=>$local_id])->find();

    // 判断是否有上级会员
    $distribution_member = M('distribution_member')->where(['member_id' => $member_id])->find();
    if (empty($distribution_member['p_member_id'])) {
        return 0;
    }

    // 查询下单比例
    $sdb_store_distribution_set = M('store_distribution_set')->where(['local_id' => $local_id, 'set_name' => 'son_shopping'])->find();

    $set_value = $sdb_store_distribution_set['set_value']/100;
    // 订单金额
    $money = $b2c_orders['total_amount'];
    $wait_bonus = bcmul($money, $set_value, 2);

    //查询会员的openid
    $openId = M('b2c_members m')
        ->field('t.openid')
        ->join("left join ".C('DB_PREFIX')."b2c_temp_user t on t.mobile = m.mobile")
        ->where(['member_id'=>$distribution_member['p_member_id']])
        ->find()['openid'];
    if(!$openId){
        return 0;
    }

    $muban = M('wx_information')->where(['wx_id' => 2])->find();
    //该店铺不推送消息
    if(!$muban){
        return 0;
    }

    // 获取会员昵称
    $nickname = get_member_msg($member_id);

    $url = $_SERVER['SERVER_NAME'].'/Member/chooseShop/local_id/'.$local_id.'/member_id/'.$distribution_member['p_member_id'];

    $cs = array(
        'touser'=>$openId,
        'template_id'=>trim($muban['template_id']),
        'url'=>$url,
        'data'=>[
            'first'=>[
                'value'=>'您好，您的朋友支付了一笔新订单',
                'color'=>"#173177",
            ],
            "keyword1"=>[
                "value"=>$order_id,
                "color"=>"#173177",
            ],
            "keyword2"=>[
                "value"=>$b2c_orders['total_amount'],
                "color"=>"#173177",
            ],
            "remark"=>[
                "value"=>"你的朋友【". $nickname ."】支付了一笔金额". $b2c_orders['total_amount'] ."的订单。预计你将收获 ". $wait_bonus ."的奖金！",
                "color"=>"#173177",
            ],
        ],
    );
    $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=";
    $obj = new \Home\Event\WeixinEvent();
    $msg = $obj->parameterPostBtn($cs,$url,1);
    return $msg;
}

/**
 * 微信关注推送给上级
 * @param $local_id 店铺id
 * @param $openId 推送给谁的微信openId
 * @param $weixinNickname 关注人的昵称
 * @param $wait_bonus 上级获得奖金
 * @return bool|int|mixed
 */
function WeixinAttentionToFatherMember($local_id, $openId, $weixinNickname, $wait_bonus){

    // 判断店铺是否开启分销功能
    $store = M('webpos_local_store')->where(['local_id' => $local_id])->find();
    if ($store['is_open_distribution'] == '0') {
        return false;
    }

    $url = $_SERVER['SERVER_NAME'].'/Member/chooseShop/local_id/'.$local_id;
    // 关注成功通知
    $muban = M('wx_information')->where(['wx_id' => 3])->find();
    //该店铺不推送消息
    if(!$muban){
        return 0;
    }
    $cs = array(
        'touser'=>$openId,
        'template_id'=>trim($muban['template_id']),
        'url'=>$url,
        'data'=>[
            'first'=>[
                'value'=>'恭喜您通过分享链接成功锁定一位会员！',
                'color'=>"#173177",
            ],
            "keyword1"=>[
                "value"=>$weixinNickname,
                "color"=>"#173177",
            ],
            "keyword2"=>[
                "value"=>date("Y-m-d H:i:s  "),
                "color"=>"#173177",
            ],
            "remark"=>[
                "value"=>"你的朋友【". $weixinNickname ."】通过扫描二维码，关注了‘永立百货超市’ ，你获得了". $wait_bonus ."的奖金！",
                "color"=>"#173177",
            ],
        ],
    );
    $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=";
    $obj = new \Home\Event\WeixinEvent();
    $msg = $obj->parameterPostBtn($cs,$url,1);
    return $msg;
}

/**
 * 微信首次生成海报
 * @param $local_id 店铺id
 * @param $openId 推送给谁的微信openId
 * @param $weixinNickname 关注人的昵称
 * @param $wait_bonus 上级获得奖金
 * @return bool|int|mixed
 */
function WeixinSonMemberCreatePosterToFatherMember($local_id, $openId, $weixinNickname, $wait_bonus){

    // 判断店铺是否开启分销功能
    $store = M('webpos_local_store')->where(['local_id' => $local_id])->find();
    if ($store['is_open_distribution'] == '0') {
        return false;
    }

    $url = $_SERVER['SERVER_NAME'].'/Member/chooseShop/local_id/'.$local_id;
    // 关注成功通知
    $muban = M('wx_information')->where(['wx_id' => 4])->find();
    //该店铺不推送消息
    if(!$muban){
        return 0;
    }
    $cs = array(
        'touser'=>$openId,
        'template_id'=>trim($muban['template_id']),
        'url'=>$url,
        'data'=>[
            'first'=>[
                'value'=>'恭喜，你有一位朋友首次生成海报！',
                'color'=>"#173177",
            ],
            "keyword1"=>[
                "value"=>$wait_bonus. '元',
                "color"=>"#173177",
            ],
            "keyword2"=>[
                "value"=>date("Y-m-d H:i:s  "),
                "color"=>"#173177",
            ],
            "remark"=>[
                "value"=>"你的朋友【". $weixinNickname ."】首次开通专属海报！你获得了". $wait_bonus ."元奖金！",
                "color"=>"#173177",
            ],
        ],
    );
    $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=";
    $obj = new \Home\Event\WeixinEvent();
    $msg = $obj->parameterPostBtn($cs,$url,1);
    return $msg;
}

/**
 * 下级关注给下级推送获得奖金
 * @param $local_id 店铺id
 * @param $openId 推送给谁的微信openId
 * @param $weixinNickname 关注人的昵称
 * @param $wait_bonus 上级获得奖金
 * @return bool|int|mixed
 */
function WeixinSonMemberGetMoney($local_id, $openId, $weixinNickname, $wait_bonus){

    // 判断店铺是否开启分销功能
    $store = M('webpos_local_store')->where(['local_id' => $local_id])->find();
    if ($store['is_open_distribution'] == '0') {
        return false;
    }

    $url = $_SERVER['SERVER_NAME'].'/Store/index/local_id/'.$local_id;
    // 关注成功通知
    $muban = M('wx_information')->where(['wx_id' => 3])->find();
    //该店铺不推送消息
    if(!$muban){
        return 0;
    }
    $cs = array(
        'touser'=>$openId,
        'template_id'=>trim($muban['template_id']),
        'url'=>$url,
        'data'=>[
            'first'=>[
                'value'=>'恭喜你获得了'.$wait_bonus.'奖金！',
                'color'=>"#173177",
            ],
            "keyword1"=>[
                "value"=>$weixinNickname,
                "color"=>"#173177",
            ],
            "keyword2"=>[
                "value"=>date("Y-m-d H:i:s  "),
                "color"=>"#173177",
            ],
            "remark"=>[
                "value"=>"【". $weixinNickname ."】首次通过怡臣优选关注".getStoreName($local_id).",你获得了". $wait_bonus ."元奖金！",
                "color"=>"#173177",
            ],
        ],
    );
    $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=";
    $obj = new \Home\Event\WeixinEvent();
    $msg = $obj->parameterPostBtn($cs,$url,1);
    return $msg;
}

/**
 * 订单完结推送消息
 * @param $local_id 店铺id
 * @param $openId 推送给谁的微信openId
 * @param $weixinNickname 关注人的昵称
 * @param $wait_bonus 上级获得奖金
 * @param $order_mount 订单金额
 * @param $less_bonus 少获取的奖金
 * @return bool|int|mixed
 */
function WeixinOrderOver($local_id, $openId, $weixinNickname, $wait_bonus, $order_mount, $less_bonus){

    // 判断店铺是否开启分销功能
    $store = M('webpos_local_store')->where(['local_id' => $local_id])->find();
    if ($store['is_open_distribution'] == '0') {
        return false;
    }

    $url = $_SERVER['SERVER_NAME'].'/Member/chooseShop/local_id/'.$local_id;
    // 关注成功通知
    $muban = M('wx_information')->where(['wx_id' => 4])->find();
    //该店铺不推送消息
    if(!$muban){
        return 0;
    }

    $less_bonus_msg = '';
    if ($less_bonus > 0) {
        $less_bonus_msg = "其中涉及部分退款，少收获￥". $less_bonus ."的奖金";
    }

    $cs = array(
        'touser'=>$openId,
        'template_id'=>trim($muban['template_id']),
        'url'=>$url,
        'data'=>[
            'first'=>[
                'value'=>'恭喜，您获得奖金！',
                'color'=>"#173177",
            ],
            "keyword1"=>[
                "value"=>$wait_bonus. '元',
                "color"=>"#173177",
            ],
            "keyword2"=>[
                "value"=>date("Y-m-d H:i:s  "),
                "color"=>"#173177",
            ],
            "remark"=>[
                "value"=>"你的朋友【". $weixinNickname ."】一笔￥". $order_mount ."的订单已经完结。你已收获 ". $wait_bonus ."的奖金！". $less_bonus_msg,
                "color"=>"#173177",
            ],
        ],
    );
    $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=";
    $obj = new \Home\Event\WeixinEvent();
    $msg = $obj->parameterPostBtn($cs,$url,1);
    return $msg;
}

/**
 * 订单完结给上级提成
 */
function orderFinishBonus($order_data){

    $local_id = $order_data['local_id'];
    $order_id = $order_data['order_id'];
    $member_id = $order_data['member_id'];

    // 判断店铺是否开启分销功能
    $store = M('webpos_local_store')->where(['local_id' => $local_id])->find();
    if ($store['is_open_distribution'] == '0') {
        return true;
    }

    // 订单代收金额队列记录表
    $b2c_queue_order_log = M('b2c_queue_order_log')->where(['local_id' => $local_id, 'order_id' => $order_id, 'member_id' => $member_id])->find();

    if ($b2c_queue_order_log) {

        // 金额提成
        $bonus = $b2c_queue_order_log['payed'];
        // 上级会员
        $p_member_id = $b2c_queue_order_log['p_member_id'];
        if (empty($p_member_id)) {
            return true;
        }

        // 累计奖金
        $distribution_member_up = M()->execute("update sdb_distribution_member set count_bonus = count_bonus + $bonus, current_bonus = current_bonus + $bonus, wait_bonus = wait_bonus - $bonus where member_id=$p_member_id and local_id = $local_id");

        // 删除代收奖金表数据
        $b2c_queue_order_log_delete = M('b2c_queue_order_log')->where(['local_id' => $local_id, 'order_id' => $order_id, 'member_id' => $member_id])->delete();

        // 修改代收奖金状态，只关联change类型为3和4
        $update_bonus_log_status = M('b2c_bonus_log')->where(['param' => ['like',"%,". $order_id .",%"], 'change' =>['in','3,4']])->save(['bonus_status' => '0']);
//        echo M('b2c_bonus_log')->_sql();

        // 订单完结记录表
        $time = time();
        $data['local_id'] = $local_id;
        $data['member_id'] = $p_member_id;
        $data['s_member_id'] = $member_id;
        $data['type'] = '0';
        $data['change'] = '7';
        $data['change_num'] = $bonus;
        $data['param'] = $member_id.','.$order_id;
        $data['time'] = $time;
        $data['msg'] = '订单完结获得了奖金';
        $bonus_log = M('b2c_bonus_log')->add($data); // 奖金日志记录

        if ($distribution_member_up == false || $b2c_queue_order_log_delete == false || $bonus_log == false || $update_bonus_log_status == false) {
            return false;
        }
        $members = M('b2c_members')->where(['member_id' => $p_member_id])->find();

        $reduce_bonus = bcmul($order_data['total_amount'], $order_data['bonus_proportion'], 2); // 总奖金
        $less_bonus  = $reduce_bonus - $bonus; //  总奖金 - 剩下的奖金 = 退款扣除的奖金

        return [$local_id, $members['openid'], $members['nickname'], $bonus, $order_data['total_amount'], $less_bonus];
    }
    return true;
}

/**
 * 当前会员退款，1如果奖金有就退款到当前会员账号，2如果当前会员上级有分销提成就必须减去退款提成
 * @param $order 订单array
 * @param $bonus 当前奖金退款
 * @param $total_money 总共退款
 * @return bool
 */
function refund_bonus($order, $bonus, $total_money){


    $local_id = $order['local_id'];
    $member_id = $order['member_id'];
    $order_id = $order['order_id'];
    $refund_bonus = bcmul($total_money, $order['bonus_proportion'], 2); // 扣除上级奖金

    // 判断店铺是否开启分销功能
    $store = M('webpos_local_store')->where(['local_id' => $local_id])->find();
    if ($store['is_open_distribution'] == '0') {
        return true;
    }

    // 查询当前会员是否有该店铺分销人员
    $distribution_member = M('distribution_member')->where(['local_id' => $local_id, 'member_id' => $member_id])->find();

    if ($distribution_member) {

        // 如果返回奖金大于0
        if (!empty($bonus) && $bonus > 0) {
            // 返还奖金
            $distribution_member_up = M()->execute("update sdb_distribution_member set current_bonus = current_bonus + $bonus where member_id=$member_id and local_id = $local_id");

            if ($distribution_member_up == false) {
                return false;
            }

            // 返还奖金写入分销人员日志
            $time = time();
            $data['local_id'] = $local_id;
            $data['member_id'] = $member_id;
            $data['type'] = '0';
            $data['change'] = '6';
            $data['change_num'] = $bonus;
            $data['param'] = $member_id.','.$order_id.','.$bonus;
            $data['time'] = $time;
            $data['msg'] = '财务退款返回奖金'.$bonus.'元';
            $bonus_log = M('b2c_bonus_log')->add($data); // 奖金日志记录
            if ($bonus_log == false) {
                return false;
            }
        }

        // 上级会员订单代收金额队列记录表
        if ($distribution_member['p_member_id']) {
            $p_member_id = $distribution_member['p_member_id'];
            $b2c_queue_order_log = M('b2c_queue_order_log')->where(['local_id' => $local_id, 'order_id' => $order_id,  'member_id' => $member_id, 'p_member_id' => $p_member_id])->find();

            if ($b2c_queue_order_log) {

                // 退款扣除上级分销人员奖金

                $refund_queue_order_log = M()->execute("update sdb_b2c_queue_order_log set payed = payed - $refund_bonus where order_id = $order_id and member_id=$member_id and local_id = $local_id and p_member_id = $p_member_id");
//                echo "update sdb_b2c_queue_order_log set payed = payed - $refund_bonus where order_id = $order_id member_id=$member_id and local_id = $local_id and 'p_member_id' = $p_member_id";
                if ($refund_queue_order_log == false) {
                    return false;
                }

                // 扣除上级代收金
                $distribution_member_up = M()->execute("update sdb_distribution_member set wait_bonus = wait_bonus - $refund_bonus where member_id=$p_member_id and local_id = $local_id");
                if ($distribution_member_up == false) {
                    return false;
                }

                // 写入上级分销人员日志
                $time = time();
                $data['local_id'] = $local_id;
                $data['member_id'] = $distribution_member['p_member_id'];
                $data['s_member_id'] = $member_id;
                $data['type'] = '1';
                $data['change'] = '4';
                $data['bonus_status'] = '1';
                $data['change_num'] = -$refund_bonus;
                $data['param'] = $member_id.','.$order_id.','.-$refund_bonus;
                $data['time'] = $time;
                $data['msg'] = '用户退款扣除奖金';
                $bonus_log = M('b2c_bonus_log')->add($data); // 奖金日志记录

                if ($bonus_log == false) {
                    return false;
                }
            }
        }
    }
    return true;
}

/**
 * 判断商品是否在活动中
 * @param $storeProductId
 * @param $localId
 * @param $limitTime
 * @return $decbin string
 */
function activityByStoreId($storeProductId, $localId, $limitTime){
    $state1 = checkProductIsGroupPromotion($storeProductId, $localId) ? 1 : 0;
    $state2 = goods_is_Goods_promotion($storeProductId, $localId) ? 2 : 0;
    $state3 = goods_is_shangou_by_limit_time($storeProductId, $localId, $limitTime) ? 4 : 0;
    $state4 = checkProductIsSpecial($storeProductId, $localId) ? 8 : 0;
    $state5 = goods_is_Order_promotion($storeProductId, $localId) ? 16 : 0;
    $decbin = decbin($state1 + $state2 + $state3 + $state4 + $state5);
    while (strlen($decbin)< 5){
        $decbin = '0'.$decbin;
    }
    return $decbin;
}